/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import {
  getMetadataColumnTree,
  getMetadataDatabaseTree,
  getMetadataTableTree
} from '@/service/modules/sqlconsole'
import { MetadataTree } from '@/service/modules/sqlconsole/types'
import { DatabaseFilled } from '@vicons/antd'
import { Table32Filled, TableInsertColumn28Filled } from '@vicons/fluent'
import { NIcon, TreeOption, useDialog } from 'naive-ui'
import { reactive, VNode, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

export function useTreeData() {
  const { t } = useI18n()

  const dialog = useDialog()
  const $router = useRouter()

  const variables = reactive({
    treeLoading: false,
    tree: [] as MetadataTree[]
  })

  // const buildTableStruct = (tree: MetadataTree[]): Record<string, any> => {
  //   const dbData: Record<string, any> = {}
  //   tree.forEach((db: MetadataTree) => {
  //     const tableData: Record<string, string[]> = {}
  //     if (db.children) {
  //       db.children.forEach((table: MetadataTree) => {
  //         if (table.children) {
  //           const columns: string[] = []
  //           table.children.forEach((column: MetadataTree) => {
  //             columns.push(column.label)
  //           })
  //           tableData[table.label] = columns
  //         }
  //       })
  //       dbData[db.label] = tableData
  //     }
  //   })
  //   return dbData
  // }

  const refresh = () => {
    variables.treeLoading = true
    getMetadataDatabaseTree()
      .then((res: MetadataTree[]) => {
        variables.tree = res
        // const tables = buildTableStruct(variables.tree)
        // $completionSqlStore.addTables(tables)
        variables.treeLoading = false
      })
      .catch(() => {
        variables.treeLoading = false
      })
  }

  const onHandleLoad = (node: MetadataTree) => {
    if (node.scopedSlots.title === 'database') {
      return new Promise<void>(async (resolve) => {
        const res = await getMetadataTableTree(node.label)
        node.children = res
        resolve()
      })
    } else {
      return new Promise<void>(async (resolve) => {
        const res = await getMetadataColumnTree(
          node.scopedSlots.parentLabel,
          node.label
        )
        node.children = res
        resolve()
      })
    }
  }

  /**
   * filter tree data
   * @param arr source tree
   * @param term search string
   */
  const filterTree = (arr: MetadataTree[], term: string) => {
    const matches: MetadataTree[] = []
    if (!Array.isArray(arr)) return matches
    arr.forEach((i: MetadataTree) => {
      if (i.label.includes(term.trim())) {
        matches.push(i)
      } else {
        const childResults = filterTree(i.children || [], term)
        if (childResults.length)
          matches.push(Object.assign({}, i, { children: childResults }))
      }
    })
    return matches
  }

  const renderTreePrefix = (info: { option: TreeOption }): VNode => {
    if ((info.option as MetadataTree).scopedSlots.title === 'database') {
      return h(NIcon, null, { default: () => h(DatabaseFilled) })
    } else if ((info.option as MetadataTree).scopedSlots.title === 'table') {
      return h(NIcon, null, { default: () => h(Table32Filled) })
    } else {
      return h(NIcon, null, { default: () => h(TableInsertColumn28Filled) })
    }
  }

  // jump to home page
  const returnBack = () => {
    dialog.warning({
      title: t('explore.return_database_page'),
      content: t('explore.return_database_page_tip'),
      positiveText: t('common.positiveText'),
      negativeText: t('common.negativeText'),
      negativeButtonProps: {
        type: 'default'
      },
      positiveButtonProps: {
        type: 'primary'
      },
      onPositiveClick: () => {
        $router.push('/home')
      }
    })
  }

  const selectTree = (
    selectedKeys: Array<string>,
    option: Array<TreeOption | null>
  ) => {
    if ((option[0] as MetadataTree).scopedSlots.title === 'database') {
      $router.push(`/explore/sqlconsole/${(option[0] as MetadataTree).label}`)
    }
  }

  return {
    variables,
    refresh,
    filterTree,
    renderTreePrefix,
    returnBack,
    selectTree,
    onHandleLoad
  }
}
